<template>
    <div>
        <!--批量上传 -->
        <el-dialog v-model="state.uploadDialogVisible" width="80%" @close="state.uploadStutas = false">
            <div v-if="!state.uploadStutas">
                <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="state.headers" action="#"
                    :disabled="state.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                    :auto-upload="false" :before-upload="beforeUpload" drag>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip text-center" slot="tip">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                    </div>
                </el-upload>
            </div>
            <div v-if="state.uploadStutas">
                <el-table ref="multipleTableRef" :data="paginatedData" style="width: 100%">
                    <el-table-column prop="id" label="序号" width="150" align="center" />
                    <el-table-column prop="workOrderName" label="工单名称" width="150" align="center" />
                    <el-table-column prop="createdDate" label="创建日期" width="150" align="center" />
                    <el-table-column prop="dueDate" label="截止日期" width="150" align="center" />
                    <el-table-column prop="income" label="收入" width="150" align="center" />
                    <el-table-column prop="workOrderDescription" label="备注" width="180" align="center" />
                </el-table>

                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="state.parsePage.pageNum" :page-sizes="[5, 10]" :page-size="state.parsePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.parsePage.total" class="mt-6">
                </el-pagination>
            </div>
            <div slot="footer" class="mt-2 flex flex-row-reverse">
                <el-button @click="state.uploadDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitFileForm" class="me-2">
                    {{ state.uploadStutas ? '导 入' : '确 定' }}
                </el-button>
            </div>
        </el-dialog>
        <!-- 添加新增窗口 -->
        <el-dialog title="新增工单信息" v-model="state.addDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="addForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="工单名称" prop="workOrderName">
                            <el-input v-model="state.editForm.workOrderName"></el-input>
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="截止日期" prop="dueDate">
                            <el-date-picker v-model="state.editForm.dueDate" type="date" placeholder="请选择截止日期" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="收入" prop="income">
                    <el-input v-model="state.editForm.income"></el-input>
                </el-form-item>

                <el-form-item label="备注" prop="workOrderDescription">
                    <el-input type="textarea" v-model="state.editForm.workOrderDescription" :rows="5" :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow">提交</el-button>
                        <el-button type="plain" @click="state.addDialogVisible = false">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 编辑工单弹出框 -->
        <el-dialog title="编辑工单信息" v-model="state.editDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="editForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="工单名称" prop="workOrderName">
                            <el-input v-model="state.editForm.workOrderName"></el-input>
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="截止日期" prop="dueDate">
                            <el-date-picker v-model="state.editForm.dueDate" type="date" placeholder="请选择截止日期" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="收入" prop="income">
                        <el-input v-model="state.editForm.income"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="workOrderStatus">
                            <el-select v-model="state.editForm.workOrderStatus" placeholder="请选择">
                                <el-option v-for="item, index in state.statusList" :key="index" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="state.activeTab == 'one'">
                        <el-form-item label="被委派人" prop="assignedToUserID">
                            <el-select v-model="state.editForm.assignedToUserID" placeholder="请选择">
                                <el-option v-for="item, index in state.employeeNames" :key="index" :label="item.Name"
                                    :value="item.EmployeeID"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="workOrderDescription">
                    <el-input type="textarea" v-model="state.editForm.workOrderDescription" :rows="5" :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow_w">提交</el-button>
                        <el-button type="plain" @click="state.editDialogVisible = false, state.editForm = {}">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog title="工单分配" v-model="state.orderWorkDialogVisible" width="50%" @close="state.orderEditForm = {}">
            <el-form ref="orderEditForm" :model="state.orderEditForm" :rules="state.rules" label-width="80px">
                <el-form-item label="被委派人" prop="assignedToUserID">
                    <el-select v-model="state.orderEditForm.assignedToUserID" placeholder="请选择">
                        <el-option v-for="item, index in state.employeeNames" :key="index" :label="item.Name"
                            :value="item.EmployeeID"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="截止日期" prop="deadline">
                    <el-date-picker v-model="state.orderEditForm.deadline" type="date" placeholder="请选择截止日期" />
                </el-form-item>

                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="addWorkOrder">提交</el-button>
                        <el-button type="plain"
                            @click="state.orderWorkDialogVisible = false, state.orderEditForm = {}">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-row class="mb-1">
            <div class="w-full flex justify-end">
                <el-autocomplete v-model="state.stateData" @change="inputSearch" :fetch-suggestions="querySearchAsync"
                    placeholder="请输入关键字" @select="handleSelect" class="mr-2">
                    <template #suffix>
                        <el-icon color="#000">
                            <Search />
                        </el-icon>
                    </template>
                </el-autocomplete>
                <el-button type="info" :icon="Avatar" @click="state.uploadDialogVisible = true" v-if="state.activeTab ==
                    'two'">导入工单数据</el-button>
                <el-button type="warning" :icon="Download" @click="downloadUser('downLoad')" v-if="state.activeTab ==
                    'two'">下载模板</el-button>
                <el-button type="success" :icon="Upload" @click="downloadUser()">{{ state.activeTab ==
                    'two' ? '导出未分配数据' : '导出已分配数据' }}</el-button>

                <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
                <el-button type="primary" :icon="Plus" @click="state.addDialogVisible = true"
                    v-if="state.activeTab == 'two'">新增</el-button>
            </div>
        </el-row>
        <el-tabs v-model="state.activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="已分配" name="one">
                <el-table :data="state.workorderList" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" fixed="left" width="50" align="center" />
                    <el-table-column prop="WorkOrderName" label="工单名称" width="150" align="center">
                        <template #default="scope">
                            {{ scope.row.workOrderData.WorkOrderName }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="AssignmentDate" label="创建日期" width="150" align="center" />
                    <el-table-column prop="Deadline" label="截止日期" width="150" align="center" />
                    <el-table-column prop="AssignedToUserID" label="被委派人" width="150" align="center">
                        <template #default="scope">
                            {{ scope.row.assignedToUserName.Name }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="CreatedUserID" label="委派人" width="150" align="center">
                        <template #default="scope">
                            {{ scope.row.workOrderData.createdUserName.Name }}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="150" align="center">
                        <template #default="scope">
                            <el-tag
                                :type="scope.row.workOrderData.Status == '0' ? 'danger' : scope.row.workOrderData.Status == '1' ? 'success' : 'warning'">
                                {{ scope.row.workOrderData.Status == "0" ? "未完成" : scope.row.workOrderData.Status == "1" ?
                                    "已完成" : "进行中" }}
                            </el-tag></template>
                    </el-table-column>
                    <el-table-column prop="Income" label="收入" width="150" align="center">
                        <template #default="scope">
                            {{ scope.row.workOrderData.Income }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="WorkOrderDescription" label="备注" width="180" align="center">
                        <template #default="scope">
                            {{ scope.row.workOrderData.WorkOrderDescription }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center" width="180">
                        <template #default="scope">
                            <el-button link type="warning" size="small" @click.prevent="openUpdata(scope.row)">
                                <el-icon>
                                    <EditPen />
                                </el-icon>
                                编辑
                            </el-button>
                            <el-button link type="danger" size="small" @click.prevent="deleteRow_w(scope.row)">
                                <el-icon>
                                    <DeleteFilled />
                                </el-icon>
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination @size-change="handlehSizeChange_w" @current-change="handlehCurrentChange_w"
                    :page-sizes="[5, 8, 10]" :page-size="state.page_w.pageSize"
                    layout="total, jumper, prev, pager, next, sizes" :total="state.page_w.total" class="mt-2">
                </el-pagination>
            </el-tab-pane>
            <el-tab-pane label="未分配" name="two">
                <el-table :data="state.unassignedWorkOrderData" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" fixed="left" width="50" align="center" />
                    <el-table-column prop="WorkOrderName" label="工单名称" width="150" align="center" />
                    <el-table-column prop="CreatedDate" label="创建日期" width="150" align="center" />
                    <el-table-column prop="DueDate" label="截止日期" width="150" align="center" />
                    <el-table-column label="状态" width="150" align="center">
                        <template #default="scope">{{ scope.row.Status == "0" ? "未完成" : "完成"
                        }}</template>
                    </el-table-column>
                    <el-table-column prop="Income" label="收入" width="150" align="center" />
                    <el-table-column prop="WorkOrderDescription" label="备注" width="180" align="center" />
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="scope">
                            <el-button link type="warning" size="small" @click.prevent="openUpdata(scope.row)">
                                <el-icon>
                                    <EditPen />
                                </el-icon>
                                编辑
                            </el-button>
                            <el-button link type="warning" size="small" @click.prevent="giveWorkOrder(scope.row)">
                                <el-icon>
                                    <EditPen />
                                </el-icon>
                                工单分配
                            </el-button>
                            <el-button link type="danger" size="small" @click.prevent="deleteRow_u(scope.row)">
                                <el-icon>
                                    <DeleteFilled />
                                </el-icon>
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination @size-change="handlehSizeChange_u" @current-change="handlehCurrentChange_u"
                    :page-sizes="[5, 8, 10]" :page-size="state.page_u.pageSize"
                    layout="total, jumper, prev, pager, next, sizes" :total="state.page_u.total" class="mt-2">
                </el-pagination>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script setup>
import { useTabsStore } from '../store/store'
import { onMounted, reactive, ref, computed } from "vue";
import { DeleteFilled, EditPen, Hide, ZoomIn, Delete, Plus, Search, Lock } from '@element-plus/icons-vue'
import { taskassignmentDelete, taskassignmentCreate, taskassignmentUpdate } from '../api/taskassignment/taskassignment'
import { formatDate } from '../utils/auth.js'
import { downloadTemplateUser, downloadUserData, analysisExcel } from '../utils/tableMethod.js'
import { workorderRead, findAllWorkOrderList, workorderUpdate, workorderDelete, workorderReadAll, workorderCreate, findWorkOrderAndID } from '../api/workorder/workorder'
const state = reactive({
    editDialogVisible: false,
    addDialogVisible: false,
    orderWorkDialogVisible: false,
    selectedIds: [],//选中的id
    selectedAssignmentID: [],//选中的分配工单id
    workorderList: [],//已分配的工单数据
    unassignedWorkOrderData: [],//未分配的工单数据
    employeeNames: [],
    workorderNames: [],
    statusList: [
        { label: '未完成', value: '0' },
        { label: '已完成', value: '1' },
        { label: '进行中', value: '2' },
    ],
    activeTab: 'one',//默认选中第一个tab
    // 分页
    page_w: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    },
    page_u: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    },
    stateData: '',//搜索框提示词
    searchType: "exact",//搜索类型
    rules: {
        workOrderName: [
            { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        dueDate: [
            { required: true, message: '请输入截止日期', trigger: 'blur' },
        ],
        workOrderDescription: [
            { required: true, message: '请输入备注', trigger: 'blur' },
        ],
        income: [
            { required: true, message: '请输入预计收入金额', trigger: 'blur' },
        ],
        workOrderStatus: [
            { required: true, message: '请选择工单状态', trigger: 'blur' },
        ],
        assignedToUserID: [
            { required: true, message: '请选择委托人', trigger: 'blur' },
        ],
        deadline: [
            { required: true, message: '请输入截止日期', trigger: 'blur' },
        ]
    },
    orderEditForm: {
        deadline: '',
        assignedToUserID: '',
        workOrderID: ''
    },
    editForm: {
        assignmentID: '',
        workOrderID: '',
        assignedToUserID: '',
        assignmentDate: '',
        deadline: '',
        income: '',
        workOrderStatus: '',
        workOrderDescription: "",
        workOrderData: {},
        assignedToUserName: {}
    },

    // 批量上传
    uploadDialogVisible: false,
    uploadStutas: false,
    // 是否禁用上传
    isUploading: false,
    // 解析后的表格数据
    parseTableData: [],
    parsePage: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    }
})
const orderEditForm = ref()
const editForm = ref()
const addForm = ref()
const useData = useTabsStore()
console.log("==========>", useData.getUserData().UserID);

// 初始化
const init = async () =>
{
    const res = await workorderRead({
        pageSize_w: state.page_w.pageSize, pageNum_w: state.page_w.pageNum,
        pageSize_u: state.page_u.pageSize, pageNum_u: state.page_u.pageNum,
        workOrderName: state.stateData, searchType: state.searchType
    })
    if (res.meta.status == 200) {

        state.workorderList = res.data.workOrderData.workOrderData
        // 已分配工单
        state.page_w.total = res.data.workOrderData.total
        state.page_w.pageSize = res.data.workOrderData.pageSize
        state.page_w.pageNum = res.data.workOrderData.pageNum

        state.unassignedWorkOrderData = res.data.unassignedWorkOrderData.unassignedWorkOrderData
        // 未分配工单
        state.page_u.total = res.data.unassignedWorkOrderData.total
        state.page_u.pageSize = res.data.unassignedWorkOrderData.pageSize
        state.page_u.pageNum = res.data.unassignedWorkOrderData.pageNum
    }
    console.log(res, "============================>");
}
// 选项卡选择
const handleTabClick = (tab) =>
{
    state.activeTab = tab.name
}
// 打开工单分配窗口
const giveWorkOrder = (row) =>
{
    state.orderWorkDialogVisible = true
    state.orderEditForm.workOrderID = row.WorkOrderID
}
// 提交分配工单
const addWorkOrder = async () =>
{
    state.orderEditForm.deadline = formatDate(state.orderEditForm.deadline)
    console.log(state.orderEditForm, "////");
    debugger
    orderEditForm.value.validate((valid) =>
    {
        if (valid) {
            ElMessageBox.confirm('确定分配工单吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () =>
            {
                const res = await taskassignmentCreate(state.orderEditForm)
                if (res.meta.status == 200) {
                    ElMessage({
                        showClose: true,
                        message: '分配成功',
                        type: 'success',
                    })
                    state.orderWorkDialogVisible = false
                    state.editForm = {}
                    init()
                }
            }).catch(() =>
            {
                ElMessage({
                    showClose: true,
                    message: '已取消',
                    type: 'info',
                })
                state.orderWorkDialogVisible = false
            })
        }
    })
}
// 打开编辑窗口
const openUpdata = (row) =>
{
    if (state.activeTab == 'one') {
        state.editForm = {
            workOrderName: row.workOrderData.WorkOrderName,
            workOrderDescription: row.workOrderData.WorkOrderDescription,
            income: row.workOrderData.Income,
            dueDate: row.Deadline,
            workOrderStatus: row.workOrderData.Status,
            assignedToUserID: row.AssignedToUserID,

            workOrderID: row.WorkOrderID,
            assignmentDate: row.AssignmentDate,//分配日期
            deadline: row.Deadline//截止日期
        }
        state.editDialogVisible = true
    } else {
        state.editForm = {
            workOrderID: row.WorkOrderID,
            workOrderName: row.WorkOrderName,
            workOrderDescription: row.WorkOrderDescription,
            income: row.Income,
            dueDate: row.DueDate,
            assignedToUserID: row.AssignedUserID,
            createdUserID: useData.getUserData().UserID,
        }

        state.editDialogVisible = true
    }
}
// 删除
const deleteRow_u = (row) =>
{
    // 弹出确认删除的对话框
    ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () =>
        {
            // 用户点击确定，执行删除操作
            const res = await workorderDelete({ workOrderID: row.WorkOrderID });
            if (res.meta.status == 200) {
                // 如果删除操作失败
                ElMessage({
                    showClose: true,
                    message: '删除成功',
                    type: 'success',
                });
            } else {
                ElMessage({
                    showClose: true,
                    message: '删除失败',
                    type: 'error',
                });
            }
            // 删除完成后执行初始化或其他操作
            init();
        })
        .catch(() =>
        {
            ElMessage('已取消');
            // 用户点击取消，不执行任何操作
        });
}
const deleteRow_w = (row) =>
{
    // 弹出确认删除的对话框
    ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () =>
        {
            // 用户点击确定，执行删除操作
            const res01 = await taskassignmentDelete({ assignmentID: row.AssignmentID });
            const res02 = await workorderDelete({ workOrderID: row.WorkOrderID });

            if (res01.meta.status == 200 && res02.meta.status == 200) {
                // 如果删除操作失败
                ElMessage({
                    showClose: true,
                    message: '删除成功',
                    type: 'success',
                });
            } else {
                ElMessage({
                    showClose: true,
                    message: '删除失败',
                    type: 'error',
                });
            }
            // 删除完成后执行初始化或其他操作
            init();
        })
        .catch(() =>
        {
            ElMessage('已取消');
            // 用户点击取消，不执行任何操作
        });
}
// 选择
const handleSelectionChange = (selection) =>
{
    if (state.activeTab == 'one') {
        console.log("选择的id", selection);
        state.selectedIds = selection.map(item => item.WorkOrderID);
        state.selectedAssignmentID = selection.map(item => item.AssignmentID);
        console.log("选择的id", state.selectedIds);
    } else {
        state.selectedIds = selection.map(item => item.WorkOrderID);
        console.log("选择的id", state.selectedIds);
    }
}
// 批量删除
const deleteAll = () =>
{
    if (state.activeTab == 'two') {
        if (state.selectedIds.length === 0) {
            // 如果没有选择序号，显示提示
            ElMessage({
                showClose: true,
                message: '请选择序号',
                type: 'warning',
            })
        } else {
            // 弹出确认删除的对话框
            ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () =>
                {
                    // 用户点击确定，执行删除操作
                    let deleteStatus = true;
                    for (const item of state.selectedAssignmentID) {
                        const res = await workorderDelete({ assignmentID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        }
                    }
                    for (const item of state.selectedIds) {
                        const res = await workorderDelete({ workOrderID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        }
                    }


                    // 根据删除操作的状态值显示相应的提示
                    if (deleteStatus) {
                        ElMessage({
                            showClose: true,
                            message: '删除成功',
                            type: 'success',
                        });
                    } else {
                        ElMessage({
                            showClose: true,
                            message: '删除失败',
                            type: 'error',
                        });
                    }

                    // 删除完成后执行初始化或其他操作
                    init();
                })
                .catch(() =>
                {
                    ElMessage('已取消')
                    // 用户点击取消，不执行任何操作
                });
        }
    } else {
        if (state.selectedIds.length === 0) {
            // 如果没有选择序号，显示提示
            ElMessage({
                showClose: true,
                message: '请选择序号',
                type: 'warning',
            })
        } else {
            // 弹出确认删除的对话框
            ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () =>
                {
                    // 用户点击确定，执行删除操作
                    let deleteStatus_w = true;
                    let deleteStatus_u = true;
                    for (const item of state.selectedAssignmentID) {
                        const res = await taskassignmentDelete({ assignmentID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus_u = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        }
                    }

                    for (const item of state.selectedIds) {
                        const res = await workorderDelete({ workOrderID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus_w = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        }
                    }

                    // 根据删除操作的状态值显示相应的提示
                    if (deleteStatus_u && deleteStatus_w) {
                        ElMessage({
                            showClose: true,
                            message: '删除成功',
                            type: 'success',
                        });
                    } else {
                        ElMessage({
                            showClose: true,
                            message: '删除失败',
                            type: 'error',
                        });
                    }

                    // 删除完成后执行初始化或其他操作
                    init();
                })
                .catch(() =>
                {
                    ElMessage('已取消')
                    // 用户点击取消，不执行任何操作
                });
        }
    }

};
// 修改
const updateRow = () =>
{
    if (state.editDialogVisible) {
        editForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定修改吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    const res01 = await workorderUpdate(state.editForm)
                    const res02 = await taskassignmentUpdate(state.editForm)
                    if (res01.meta.status == 200 || res02.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '修改成功',
                            type: 'success',
                        })
                        state.editDialogVisible = false
                        state.editForm = {}
                        init()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
    if (state.addDialogVisible) {
        addForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定新增吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    console.log(state.editForm, "获取的值");
                    state.editForm.deadline = formatDate(state.editForm.dueDate)
                    state.editForm.dueDate = formatDate(state.editForm.dueDate)

                    // 当前时间获取赋值
                    state.editForm.createdDate = new Date().toLocaleDateString().replace(/\//g, '-');
                    state.editForm.createdUserID = useData.getUserData().UserID
                    const res = await workorderCreate(state.editForm)
                    if (res.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '新增成功',
                            type: 'success',
                        })
                        state.addDialogVisible = false
                        state.editForm = {}
                        init()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
}
const updateRow_w = () =>
{
    if (state.editDialogVisible) {
        editForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定修改吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    const res = await workorderUpdate(state.editForm)
                    if (res.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '修改成功',
                            type: 'success',
                        })
                        state.editDialogVisible = false
                        state.editForm = {}
                        init()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
    if (state.addDialogVisible) {
        addForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定新增吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {

                    // 当前时间获取赋值
                    state.editForm.createdDate = new Date().toLocaleDateString()
                    state.editForm.createdUserID = useData.getUserData().UserID
                    const res = await workorderCreate(state.editForm)
                    if (res.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '新增成功',
                            type: 'success',
                        })
                        state.addDialogVisible = false
                        state.editForm = {}
                        init()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
}
// 分页
const handlehSizeChange_w = (val) =>
{
    state.page_w.pageSize = val;
    state.page_w.pageNum = 1;
    init()
}
// 分页
const handlehCurrentChange_w = (val) =>
{
    state.page_w.pageNum = Math.ceil(val);
    init()
}
// 分页
const handlehSizeChange_u = (val) =>
{
    state.page_u.pageSize = val;
    state.page_u.pageNum = 1;
    init()
}
// 分页
const handlehCurrentChange_u = (val) =>
{
    state.page_u.pageNum = Math.ceil(val);
    init()
}
// 查询所有的工单搜索词
const findWorderOrderNames = async () =>
{
    const { workOrderNameList } = await findAllWorkOrderList()
    state.workorderNames = workOrderNameList
    console.log(state.workorderNames, "搜索词")

    state.workorderNames = state.workorderNames.map(function (item)
    {
        return { value: item };
    });
}
// 获取所有的人员名称
const getAllEmployeeNames = async () =>
{
    const { workOrderAndID } = await findWorkOrderAndID()
    state.employeeNames = workOrderAndID
}

//  搜索查找
const inputSearch = () =>
{
    state.searchType = 'fuzzy' //执行模糊搜索
    init()
}
// 搜索
let timeout
// 触发过滤条件
const querySearchAsync = (queryString, cb) =>
{
    const results = queryString
        ? state.workorderNames.filter(createFilter(queryString))
        : state.workorderNames

    clearTimeout(timeout)
    timeout = setTimeout(() =>
    {
        cb(results)
    }, 3000 * Math.random())
}
// 创建过滤
const createFilter = (queryString) =>
{
    return (restaurant) =>
    {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// 搜索框选择
const handleSelect = (item) =>
{
    state.stateData = item.value
    init()
    console.log(state.stateData, "搜索词")
}
// 下载模板or下载数据表
const downloadUser = async (key) =>
{
    const colsList = [ //设置表格的宽度
        {
            wpx: 50, //序号
        },
        {
            wpx: 100, //工单名称
        },
        {
            wpx: 100, //创建日期
        },
        {
            wpx: 100, //截止日期
        },
        {
            wpx: 100, //收入
        },
        {
            wpx: 150, //备注
        }
    ];

    const positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 4 }
    if (key == 'downLoad') {
        const instructions = [
            "导入说明.\n" +
            "1. 请不要改动Excel表结构并严格按照导入规则进行导入，否则将导入失败或出现不可预知的问题.\n" +
            "2. 请使用手机号码或者邮箱作为用户登录账号，用户的邮箱和手机号必须保证唯一性.\n" +
            "3. 登录密码默认为123456.\n" +
            "4. 所属部门名称必须与系统内已有的部门名称一致，否则将导致无法正常分配部门.\n" +
            "5. 所属权限名称必须与系统内已有的权限名称一致，否则将导致无法正常分配权限.\n" +
            "6. 请勿修改数据表结构，否则将导入失败的注明."
        ]
        const tableHeader = [
            "序号",
            "工单名称",
            "备注",
            "创建日期",
            "截止日期",
            "收入",
        ]
        const tableNameTemplate = "工单模板表"
        downloadTemplateUser(instructions, tableHeader, colsList, tableNameTemplate, positionObj)
    }
    else {
        if (state.activeTab === "two") {
            const tableName = "工单数据表(未分配)"
            const tableData = await workorderReadAll()
            for (let item of tableData.data.untableData.rows) {
                if (item.Department) {
                    item.Department = item.Department.DepartmentName;
                }
                // 去除DepartmentID字段
                delete item.AssignedUserID;
                delete item.Status;
                delete item.CreatedUserID;
            }
            const tableHeader = [
                "序号",
                "工单名称",
                "备注",
                "创建日期",
                "截止日期",
                "收入",
            ]
            console.log(tableData, "未分配工单单数据");
            let dataRows = tableData.data.untableData.rows.map(obj => Object.values(obj));
            let titleRow = ['工单数据表(未分配)'];
            console.log("===========>未分配数据", dataRows);
            downloadUserData(tableHeader, titleRow, dataRows, colsList, tableName, positionObj)
        } else {
            const tableHeader = [
                "序号",
                "创建日期",
                "截止日期",
                "被委托人",
                "收入",
                "状态",
                "备注",
                "工单名称",
                "委托人",

            ]
            const tableName = "工单数据表(已分配)"
            const tableData = await workorderReadAll()
            for (let item of tableData.data.tableData.rows) {
                console.log(item.assignedToUserName.Name, "=====>");
                if (item.assignedToUserName) {
                    item.assignedToUserName = item.assignedToUserName.Name;
                }
                if (item.workOrderData) {
                    item.income = item.workOrderData.Income;
                    item.status = item.workOrderData.Status;
                    item.WorkOrderDescription = item.workOrderData.WorkOrderDescription;
                    item.WorkOrderName = item.workOrderData.WorkOrderName;
                }
                if (item.workOrderData.createdUserName) {
                    item.createdUserName = item.workOrderData.createdUserName.Name;
                }
                // 去除DepartmentID字段
                delete item.AssignmentID;
                delete item.workOrderData;
                delete item.AssignedToUserID
            }
            const positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 7 }
            console.log(tableData, "已分配工单单数据");
            let dataRows = tableData.data.tableData.rows.map(obj => Object.values(obj));
            let titleRow = ['工单数据表(已分配)'];
            console.log("===========>已分配数据", dataRows);
            downloadUserData(tableHeader, titleRow, dataRows, colsList, tableName, positionObj)
        }

    }
}

//上传文件之前的钩子
const beforeUpload = async (file) =>  
{
    const tableJson = await analysisExcel(file)
    state.uploadStutas = true
    console.log(tableJson, "========>1111");
    // 值为空格的参数剔除
    for (let index = 0; index < tableJson.tableData.length; index++) {
        const item = tableJson.tableData[index];
        console.log("===[]", state.parseTableData);
        if (item != '') {
            state.parseTableData[index] = {
                id: item[0],
                workOrderName: item[1],
                workOrderDescription: item[2],
                createdDate: item[3],
                dueDate: item[4],
                income: item[5],
                createdUserID: useData.getUserData().UserID
            }
        }
    }
    state.parsePage.total = state.parseTableData.length
    console.log(state.parseTableData, "=====111===>");
}
const upload = ref()
// 提交上传文件
const submitFileForm = () =>
{
    console.log(state.userTypeNameList, "=======>");
    if (state.uploadStutas) {
        for (let index = 0; index < state.parseTableData.length; index++) {
            state.editForm = state.parseTableData[index];
            console.log(state.editForm, "即将注册的部门数据");
            workorderCreate(state.editForm).then(res =>
            {
                ElMessage({
                    showClose: true,
                    message: '新增成功',
                    type: 'success',
                })
                state.uploadStutas = false
                state.uploadDialogVisible = false
                init()
            })
        }

    } else {
        upload.value.submit();
    }
}
// 解析数据分页
// 分页
const handleSizeChange = (val) =>
{
    console.log(`每页 ${val} 条`)
    state.parsePage.pageSize = val
}
const handleCurrentChange = (val) =>
{
    console.log(`当前页: ${val}`);
    state.parsePage.pageNum = val;
}
// 计算分页数据
const paginatedData = computed(() =>
{
    const startIndex = (state.parsePage.pageNum - 1) * state.parsePage.pageSize;
    const endIndex = startIndex + state.parsePage.pageSize;
    return state.parseTableData.slice(startIndex, endIndex);
})
onMounted(() =>
{
    init()
    findWorderOrderNames()
    getAllEmployeeNames()
})
</script>

<style lang="sass" scoped>

</style>